package com.zyx.mall.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zyx.mall.entity.User;
import com.zyx.mall.entity.queryObject.UserQuery;
import com.zyx.mall.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

/**
 * <p>
 * 用户接口
 * </p>
 *
 * @author zyx
 * @since 2023-01-09
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    //用户注册
    @PostMapping("/register")
    public String userRegister(@RequestBody User user) {
        //逻辑校验
        String phone = user.getPhone();
        if (phone.length()!=11){
            return "手机号不符合要求";
        }
        String password = user.getPassword();
        if (password.length()<6){
            return "密码长度太短";
        }
        //判断该用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",phone);
        User one = userService.getOne(queryWrapper);
        if (one!=null){
            //该用户已经存在
            return "该用户已经注册过了";
        }

        boolean rows = userService.save(user);
        return "ok";
    }

    //用户登录
    @GetMapping("/login")
    public User userLogin(UserQuery userQuery) {
        //判断该用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",userQuery.getPhone())
                .eq("is_deleted",0);
        User user = userService.getOne(queryWrapper);
        if (user==null){
            //该用户不存在
            return new User();
        }
        if (!user.getPassword().equals(userQuery.getPassword())){
            //密码不对
            return new User();
        }

        return user;
    }

    //更新用户账号状态
    @PutMapping("/update")
    public Boolean userUpdate(@RequestBody User user) {
        System.out.println(user);
        return userService.updateById(user);
    }

    //用户删除
    @DeleteMapping("/del")
    public Boolean userDel(String id) {
        return userService.removeById(id);
    }

    //分页查询
    @GetMapping("/list/page")
    public Page listPage(UserQuery userQuery,Integer currentPage,Integer pageSize){
        String id = userQuery.getId();
        String phone = userQuery.getPhone();
        String name = userQuery.getName();
        Page<User> page = new Page<>(currentPage,pageSize);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(id),"id",id)
                .like(StringUtils.isNotEmpty(name),"name",name)
                .eq(StringUtils.isNotEmpty(phone),"phone",phone);
        userService.page(page,queryWrapper);
        return page;
    }
}

